package com.fingard.dsp.bank.directbank.hbb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.hbc01.HBC01BatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author Parker on 2019-08-15.
 * @version 1.0
 */
public class HBB01BatPayRec extends HBB01Base implements IBatPayRec {
    /**
     * 批量代付提交
     *
     * @param p_req1988 批量代付请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            //======拼接报文======
            //拼接请求报文体
            HBB01Header bankHeader = new HBB01Header();
            bankHeader.serviceId = "CBE030101";
            bankHeader.serialNo = p_req1988.reqHeader.transSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("body");
            if (p_req1988.reqHeader.commandCode.equals("198802")) {//代发工资
                xmlWriter.writeElementString("businessCode", "030101");
            } else {
                xmlWriter.writeElementString("businessCode", "030201");
            }
            xmlWriter.writeElementString("payAccount", p_req1988.ownAct);//付款账号
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(Format.Date10Format.parse(p_req1988.payDate));
            calendar.add(Calendar.MONTH, -1);
            String dateTime = Format.Date8Format.format(calendar.getTime());
            xmlWriter.writeElementString("payMonth", dateTime.substring(0, 6));//代发月份yyyyMM  取支付时间上一个月
            xmlWriter.writeElementString("totalNumber", p_req1988.totalNum);//总笔数
            xmlWriter.writeElementString("totalAmount", p_req1988.totalAmt);//总金额
            xmlWriter.writeElementString("currencyType", convertCurToBank(p_req1988.ownCur + "for1988"));//币种-人民币
            xmlWriter.writeElementString("dealFlag", getBankConfig().getValueAsString("dealWay"));//涉案可疑名单处理方式
            int tmpCount = 0;
            xmlWriter.writeStartElement("list");
            while (p_req1988.readRecord()) {
                tmpCount++;
                xmlWriter.writeStartElement("row");
                xmlWriter.writeElementString("recAccount", p_req1988.readedDetail.recAct);//收款账号
                xmlWriter.writeElementString("recAccountName", p_req1988.readedDetail.recName);//收款方户名
                xmlWriter.writeElementString("payAmount", p_req1988.readedDetail.payAmount);//付款金额
                xmlWriter.writeElementString("payRem", p_req1988.readedDetail.memo);//备注
                xmlWriter.writeElementString("employeeId", p_req1988.readedDetail.askNumber);//对账码
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
            if (tmpCount != Integer.parseInt(p_req1988.totalNum)) {
                retAts.respCode = "-1";
                retAts.respInfo = "总笔数与循环数不一致";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.writeRetToATS();
                return retAts;
            }
            xmlWriter.writeEndElement();
            //写入签名数据
            xmlWriter.writeElementString("sign", getSingData(xmlWriter));
            xmlWriter.writeEndDocument();
            String[] bankResult = sendToBank(xmlWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/ebank/head/retCode");
                    String respInfo = tmpBkReader.getFirstText("/ebank/head/retMessage");

                    retAts.respCode = "0";
                    retAts.respInfo = respCode + "+" + respInfo;
                    retAts.reqSeqID = p_req1988.reqBatchNO;
                    if (respCode != null && respCode.equals("000000")) {
                        retAts.transState = respCode + "+" + tmpBkReader.getFirstText("/ebank/body/orderState");
                    } else {
                        retAts.transState = respCode;
                    }
                    retAts.payInfoCode = retAts.transState;

                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
                //记录批次号对应的银行支付批次号，供查询状态接口使用
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1988.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1988.reqBatchNO, tmpBkReader.getFirstText("/ebank/body/batchNo")});
            } else if (bankResult[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = bankResult[1];
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = bankResult[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = bankResult[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常：" + e);
            e.printStackTrace();
        } finally {
            conn.close();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        Connection conn = FGBiz.getLocalDbConn();
        try {
            HBB01Header bankHeader = new HBB01Header();
            bankHeader.serviceId = "CBE030302";
            Integer total = Integer.parseInt(p_req1998.totalNum);//总笔数
            String pageSize = getBankConfig().getValueAsString("pageSize");//每页查询数量
            int curPage = 0;
            while (total > 0 && (StringHelper.isNullOrEmpty(retAts.respInfo))) {
                total -= Integer.parseInt(pageSize);
                //======拼接报文======
                //拼接请求报文体
                bankHeader.serialNo = getQryTransID();
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("body");
                Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1998.reqBatchNO, p_req1998.reqHeader.bankCode});
                if (selMap.size() > 0) {
                    xmlWriter.writeElementString("batchNo", selMap.get("BANKREQSEQID").toString());//批次号
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "交易流水号关联映射异常，请检查";
                    retAts.writeBeforeDetail();
                    retAts.writeAfterDetail();
                    return retAts;
                }
                xmlWriter.writeElementString("turnPageBeginPos", String.valueOf(curPage * Integer.parseInt(pageSize) + 1));//翻页数据起始位置
                xmlWriter.writeElementString("turnPageShowNum", pageSize);//翻页一次显示数量
                curPage++;//页码+1
                xmlWriter.writeEndElement();
                //写入签名数据
                xmlWriter.writeElementString("sign", getSingData(xmlWriter));
                xmlWriter.writeEndDocument();

                String[] bankResult = sendToBank(xmlWriter.toXmlString());
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String respCode = tmpBkReader.getFirstText("/ebank/head/retCode");
                        String respInfo = tmpBkReader.getFirstText("/ebank/head/retMessage");
                        if (respCode != null && respCode.equals("000000")) {
                            retAts.respCode = "0";
                            retAts.respInfo = respCode + "+" + tmpBkReader.getFirstText("/ebank/body/orderState");
                            String payName = tmpBkReader.getFirstText("/ebank/body/payAccountName");
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.writeBeforeDetail();
                            while (tmpBkReader.read("/ebank/body/list/row")) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                tmpRetDetail.payAct = p_req1998.ownAct;
                                tmpRetDetail.payName = payName;
                                tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("recAccount");//收款人号
                                tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("recAccountName");//收款人名
                                tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("employeeId");//批内流水号
                                tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("payAmount");//金额
                                tmpRetDetail.memo = "";//备注
                                tmpRetDetail.result = respCode + "+" + tmpBkReader.readedXElement.getSingleText("orderState");
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = respInfo;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = bankResult[1];
                }
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        } finally {
            conn.close();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
